package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.Book;
import com.example.demo.mapper.BookMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {


    @Resource
    private BookMapper bookMapper;


    //查询所有
    public List<Book> findAllBook(){
        return bookMapper.selectList(null);
    }

    //待条件查询
    public List<Book> searchBooks(Book book){
       /* LambdaQueryWrapper<Book> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(book.getName()!=""&&book.getName()!=null,Book::getName,book.getName());
        queryWrapper.eq(book.getCategory()!=""&&book.getCategory()!=null,Book::getCategory,book.getCategory());
        queryWrapper.eq(book.getAuthor()!=""&&book.getAuthor()!=null,Book::getAuthor,book.getAuthor());
        return bookMapper.selectList(queryWrapper);*/
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper();
        if (book.getName() !=null && book.getName() !=""){
            queryWrapper.like(Book::getName,book.getName());
        }
        if (book.getCategory() !=null && book.getCategory() !=""){
            queryWrapper.like(Book::getCategory,book.getCategory());
        }
        if (book.getAuthor() !=null && book.getAuthor() !=""){
            queryWrapper.like(Book::getAuthor,book.getAuthor());
        }
        return  bookMapper.selectList(queryWrapper);
    }


    public IPage getPage(int pageNum, int size, Book book) {

        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper();
        if (book.getName() !=null && book.getName() !=""){
            queryWrapper.like(Book::getName,book.getName());
        }
        if (book.getCategory() !=null && book.getCategory() !=""){
            queryWrapper.like(Book::getCategory,book.getCategory());
        }
        if (book.getAuthor() !=null && book.getAuthor() !=""){
            queryWrapper.like(Book::getAuthor,book.getAuthor());
        }
        IPage bookPage = new Page(pageNum, size);//参数一是当前页，参数二是每页个数
        return bookMapper.selectPage(bookPage, queryWrapper);

    }



    //新增
    public void addBook(Book book){
        bookMapper.insert(book);
    }

    public void deleteBook(int id) {
        bookMapper.deleteById(id);
    }

    public Book findBookById(int id) {
        return bookMapper.selectById(id);
    }

    public void updateBook(Book book) {
        bookMapper.updateById(book);
    }
}
